import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { View, StyleSheet, StatusBar } from 'react-native'
import Orientation from 'react-native-orientation-locker'
import CustomHeader from 'src/components/header'
import { NAVIGATIONBAR_HEIGHT } from 'src/utils/ScreenUtil'
import { DismissLoading } from 'src/utils/ToastUtil'

export default class BasePage extends Component {
  constructor (props) {
    super(props)
    Orientation.lockToPortrait()
    if (this.componentWillFocus) {
      this.componentWillFocus = this.componentWillFocus.bind(this)
      this.willFocusSubscription = this.props.navigation.addListener(
        'willFocus',
        this.componentWillFocus
      )
    }
    if (this.componentDidFocus) {
      this.componentDidFocus = this.componentDidFocus.bind(this)
      this.didFocusSubscription = this.props.navigation.addListener(
        'didFocus',
        this.componentDidFocus
      )
    }
  }

  render () {
    const { header } = this.state || {}
    return (
      <View
        style={[
          styles.container,
          header &&
          header.headerBg !== 'transparent' &&
          styles.transparentPadding
        ]}
      >
        {this.renderNavigationBar(header)}
        {this.childRender()}
      </View>
    )
  }

  renderNavigationBar (header) {
    return header ? (
      <CustomHeader {...header} goBack={this.goBack}>
        {this.renderNavigationBarChild()}
      </CustomHeader>
    ) : (
      <StatusBar
        animated={false}
        hidden={false}
        backgroundColor={'transparent'}
        barStyle={'dark-content'}
        translucent={true}
        networkActivityIndicatorVisible={false}
      />
    )
  }

  renderNavigationBarChild () {}

  childRender () {}

  goBack = () => {
    this.props.navigation.goBack()
  }

  componentWillUnmount () {
    this.willFocusSubscription && this.willFocusSubscription.remove()
    this.didFocusSubscription && this.didFocusSubscription.remove()
    DismissLoading()
  }

  componentDidCatch (error, info) {
    // console.warn('componentDidCatch', error, info)
  }
}
BasePage.propTypes = {
  navigation: PropTypes.object
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative'
  },
  transparentPadding: {
    paddingTop: NAVIGATIONBAR_HEIGHT
  }
})
